package com.example.interceptor;

import com.alibaba.fastjson.JSON;
import com.example.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Base64;

/**
 * @desc 拦截器，解析token
 * @author shishumin
 * @date 2024/10/11 17:34
 */
@Slf4j
public class SSOInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (StringUtils.equalsIgnoreCase(request.getHeader("Is-Public-Resource"), "true")) {
            UserSessionHolder.setCurrentUser(null);
            return true;
        }
        if (StringUtils.equalsIgnoreCase(request.getHeader("Is-Inner-Request"), "true")) {
            UserSessionHolder.setCurrentUser(null);
            return true;
        }
        String userKey = request.getHeader(Constants.TOKEN_USER_KEY);
        if (StringUtils.isNotBlank(userKey)) {
            SSOSessionData sessionData = new SSOSessionData("", userKey, "", "");
            UserSessionHolder.setCurrentUser(sessionData);
            return true;
        }
        try {
            String requestURI = request.getRequestURI();
            log.info("requestURL:{}",requestURI);
            String base64edData = request.getHeader("X-UserInfo");
            if (StringUtils.isNotBlank(base64edData)) {
                SSOSessionData sessionData = JSON.parseObject(Base64.getDecoder().decode(base64edData), SSOSessionData.class);
                UserSessionHolder.setCurrentUser(sessionData);
                log.info("登录操作人:{}",sessionData.getUsername());
            }
        } catch (Exception e) {
            response.setStatus(HttpStatus.FORBIDDEN.value());
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserSessionHolder.clearCurrentUser();
    }

}